<template>
  <div class="resource-table">
    <u-table
      v-if="resourceData && resourceData.data && resourceData.data.items.length > 0 && !tableFlag"
      ref="tableRef"
      :data="resourceData.data.items"
      :row-class-name="tableRowClassName"
      :height="tableHeight"
      :highlight-current-row="false"
      :row-height="118"
      :border="true"
      beautify-table
      header-drag-style
      use-virtual
      row-key="mediumId"
      class="fb-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      fit
      @sort-change="sortMethod"
      @select="selectTable"
      @select-all="selectTable"
      @selection-change="handleSelectionChange">
      <u-table-column
        align="center"
        type="selection"
        min-width="50"
        width="50"/>
      <u-table-column :fixed="!showMobilePage?'left':false" label="账号信息" width="230px" class-name="edit-column">
        <template slot-scope="scope">
          <i v-if="hasRouteAuth('medium:dataEdit:createInfo') && scope.row.isEditAuth" class="edit-info" @click="toEdit(scope.row, 'resourceEdit')" />
          <ResourceInfo :scope="scope" :table-list-setting="tableListSetting"/>
        </template>
      </u-table-column>
      <TableColumn
        v-for="column in columnList"
        :key="column.fieldName"
        :platform="activeTabs"
        :column="column"
        @showOrderDialog="showOrderDialog"
        @editRemarkMaskShow="editRemarkMaskShow"
        @editCaseMaskShow="editCaseMaskShow"
        @editInfo="editInfo"
        @toEdit="toEdit"
      />
      <u-table-column :width="56" fixed="right" align="left" label="操作" >
        <template slot-scope="scope">
          <div class="btn-list">
            <ToolTip class="mb16" content="查看详情" @click.native="toDetail(scope)">
              <div class="btn-icon look"/>
            </ToolTip>
            <ToolTip class="mb16" content="编辑账号">
              <MoreOpeator
                :list="[
                  {label: '账号信息', handelClick: ()=> toEdit(scope.row,'resourceEdit'),disabled: !(hasRouteAuth('medium:dataEdit:createInfo') && scope.row.isEditAuth), tip: getTip('medium:dataEdit:createInfo', scope), type: getType('medium:dataEdit:createInfo', scope)},
                  {label: '更多账号信息', handelClick: ()=> toEdit(scope.row,'moreAccountInfoEdit'),disabled: !(hasRouteAuth('medium:dataEdit:moreAccount') && scope.row.isEditAuth), tip: getTip('medium:dataEdit:moreAccount', scope), type: getType('medium:dataEdit:moreAccount', scope)},
                  {label: '上刊信息', handelClick: ()=> toEdit(scope.row,'journalEdit'),disabled: !(hasRouteAuth('medium:dataEdit:journalInfo') && scope.row.isEditAuth), tip: getTip('medium:dataEdit:journalInfo', scope), type: getType('medium:dataEdit:journalInfo', scope)},
                  {label: '签约信息', handelClick: ()=> toEdit(scope.row,'signInfoEdit'),disabled: !(hasRouteAuth('medium:dataEdit:signInfo') && scope.row.isEditAuth), tip: getTip('medium:dataEdit:signInfo', scope), type: getType('medium:dataEdit:signInfo', scope)},
                  {label: '更多运营信息', handelClick: ()=> toEdit(scope.row,'otherInfoEdit'),disabled: !(hasRouteAuth('medium:dataEdit:otherInfo') && scope.row.isEditAuth), tip: getTip('medium:dataEdit:otherInfo', scope), type: getType('medium:dataEdit:otherInfo', scope)}
                ]"
              >
                <div slot="button" class="btn-icon edit"/>
              </MoreOpeator>
            </ToolTip>
            <ToolTip content="改名记录" @click.native="toChangeName(scope.row)">
              <div class="btn-icon changeName"/>
            </ToolTip>
          </div>
        </template>
      </u-table-column>
    </u-table>
    <empty-placeholder v-else style="margin-bottom: 24px" />
    <el-row v-if="showMobilePage" type="flex" justify="left">
      <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
      <el-pagination
        v-if="resourceData && resourceData.data && resourceData.data.total > 0"
        :current-page="resourceData.data.page "
        :page-size="resourceData.data.perPage"
        :total="resourceData.data.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        layout="total, prev, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <fixed-pagination>
      <slot v-if="showMobilePage" name="mobile-footer" />
      <tableFooter
        v-if="resourceData && resourceData.data && resourceData.data.items.length > 0"
        :resource-data="resourceData"
        :select-item="multipleSelectionAll"
        :can-merge="canMerge"
        show-mobile-icon
        @toMerge="toMerge"
        @mergeShow="mergeShow"
        @quicklyCreate="quicklyCreate"
        @clearMixinSelection="clearMixinSelection"
        @handleCurrentChange="handleCurrentChange"
        @getMediumData="getMediumData"
        @handleSizeChange="handleSizeChange"
        @handleCheckAllChange="handleCheckAllChange"
        @signDialogOpen="setSignStatusDialogOpen"
      />
      <slot v-if="showMobilePage" name="mobile-create" />
    </fixed-pagination>

    <EditRemarkMask ref="editRemarkMask" @mutedUpdateMediumList="mutedUpdateMediumList" />
    <EditCaseMask ref="editCaseMask" @mutedUpdateMediumList="mutedUpdateMediumList" />
    <ResourceNameConfig :table-visible="tableVisible" :active-medium-id="activeMediumId" @handleClose="handleClose" />
    <newMergeList ref="newMergeList" @freshData="freshData"/>
    <order-list-dialog ref="orderListDialog" :resource-medium-id="resourceMediumId" />
    <SetSignStatus ref="setSignStatusRef" :loading="signSetLoading" @signStatusChange="signStatusChange" />

    <EditInfoDialog ref="EditInfoDialogRef" :platform="activeTabs" @getMediumData="getMediumData" />
    <!-- 编辑弹窗 -->
    <div class="edit-dialog">
      <resourceDialog ref="resourceEdit" @success="getMediumData"/>
      <editMoreAccount ref="moreAccountInfoEdit" @success="getMediumData"/>
      <editJournalInfo ref="journalEdit" @success="getMediumData"/>
      <editSignInfoDialog ref="signInfoEdit" @success="getMediumData"/>
      <editMoreOperateInfo ref="otherInfoEdit" @success="getMediumData"/>
    </div>
  </div>
</template>
<script>
/**
 * 这个组件的功能：
 * 表格数据展示
 * 批量删除
 */
// api
import { setSignStatus } from '@/api/resource';
// components
import orderListDialog from '@/components/resource/orderList/orderListDialog';
import EditRemarkMask from '@/components/MediumPage/EditRemarkMask';
import tableFooter from '@/components/resource/filter/tableFooter';
import SetSignStatus from '@/components/resource/setSignStatus';
import newMergeList from '@/components/resource/merge/newMergeList';
import EditCaseMask from '@/components/MediumPage/EditCaseMask';
import tableTool from '@/components/resource/filter/tableTool';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import frameContent from '@/components/Common/frameContent';
import TableColumn from './model/tableColumn';
import ResourceInfo from './model/resourceInfo';
import EditInfoDialog from './model/editInfoDialog.vue';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
// 编辑弹窗
import resourceDialog from '@/views/resource/components/resourceDialog';
import editJournalInfo from '@/views/resource/components/editJournalInfo';
import editMoreAccount from '@/views/resource/components/editMoreAccount';
import editMoreOperateInfo from '@/views/resource/components/editMoreOperateInfo';
import editSignInfoDialog from '@/views/resource/components/editSignInfoDialog';
// img
import setting from '@/assets/setting.png';

import { getSupplierType, signStatusFilter } from '@/filters/status';
import opeatorFn from '@/views/resource/mixins/opeatorFn';
import tableSelections from '@/mixins/tableSelections';
import { getDeptFullName } from '@/filters/dept';
import { standardFormat } from '@/filters/date';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { expiredTypeClass } from '@/views/signUp/components/status';
import { getResouceInfo } from '@/api/resource';

export default {
  filters: {
    standardFormat, getDeptFullName, getSupplierType,
    microTaskFilter(task) {
      if (!task && task !== 0) return '--';
      const taksArr = ['否', '是'];
      return taksArr[task];
    }
  },
  components: {
    frameContent,
    EditRemarkMask,
    EditCaseMask,
    tableTool,
    tableFooter,
    SetSignStatus,
    EmptyPlaceholder,
    orderListDialog,
    newMergeList, TableColumn, EditInfoDialog, ResourceInfo,
    MoreOpeator,
    resourceDialog, editJournalInfo, editMoreAccount, editMoreOperateInfo, editSignInfoDialog,
    ResourceNameConfig: () => import('@/components/Configuration/module/resourceNameConfig')
  },
  mixins: [tableSelections, opeatorFn],
  props: {
    // 平台，1:微信 2: 微博 3:小红书 4.抖音 5:更多  6:直播 7:B站
    activeTabs: {
      type: String | Number,
      default: ''
    },
    resourceData: {
      type: Object,
      default: null
    },
    tableListSetting: {
      type: Array,
      default: () => {
        return [];
      }
    },
    tabs: {
      type: Array,
      default: null
    },
    tableHeight: {
      type: String,
      default: '1000'
    },
    curView: {
      type: Object | String,
      default: () => ({})
    }
  },
  data() {
    return {
      setting,
      selectItem: [],
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'mediumId', // 唯一表示字段
      signSetLoading: false,
      tableVisible: false,
      activeMediumId: null,
      resourceMediumId: 0,
      canMerge: true,
      isUmyTable: true,
      tableFlag: false,
      mergeData: [] // 合并列表
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAll() {
      return this.activeTabs === '';
    },
    columnList() {
      let ans = [];
      const result = [];
      this.tableListSetting.forEach(i => {
        ans = ans.concat(i.children);
      });
      if (this.curView && this.curView.data && !Array.isArray(this.curView.data)) {
        const { sortList } = this.jsonParse(this.curView.data);
        sortList.forEach(i => {
          const findItem = ans.find(j => j.fieldName === i.fieldName);
          if (findItem) {
            result.push(findItem);
          }
        });
      }
      return this.curView && this.curView.data && !Array.isArray(this.curView.data) ? result : ans;
    }
  },
  watch: {
    multipleSelectionAll: {
      handler: function(newVal) {
        this.canMerge = true;
        if (newVal.length !== 0) {
          const self = this;
          self.$nextTick(() => {
            const platformId = newVal[0].platformId;
            if (newVal.some(el => el.platformId !== platformId)) { // 存在不同平台
              self.canMerge = false;
              return;
            }
            self.mergeData = newVal;
          });
        }
      },
      deep: true
    },
    activeTabs: {
      handler: function() {
        this.$nextTick(() => {
          if (this.clearMixinSelection) this.clearMixinSelection();
        });
      }
    },
    resourceData: {
      handler: function(val, oldval) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.data.items);
        });
      },
      deep: true// 对象内部的属性监听，也叫深度监听
    },
    columnList: {
      handler: function(val, oldval) {
        this.tableFlag = true;
        this.$nextTick(() => {
          this.tableFlag = false;
        });
      },
      deep: true
    }
  },
  methods: {
    signStatusFilter,
    hasRouteAuth,
    expiredTypeClass,
    freshData() {
      this.multipleSelectionAll = [];
      this.getMediumData();
    },
    jsonParse(str, defaultVal = {}) {
      if (typeof str !== 'string') return str;
      try {
        return JSON.parse(str);
      } catch (error) {
        return defaultVal;
      }
    },
    toMerge() { // 合并资源
      if (this.multipleSelectionAll.length <= 1) {
        this.$message.warning('请至少选择两个相同平台的账号资源');
        return;
      }
      this.$refs['newMergeList'].openDialog(this.multipleSelectionAll);
    },
    // 表格选中
    handleCheckAllChange(selectAll) {
      if (selectAll) {
        this.$refs.tableRef.toggleAllSelection();
      } else {
        this.clearSelection();
      }
    },
    clearSelection() {
      if (this.clearMixinSelection) this.clearMixinSelection();
    },
    // 选择表格
    tableSelectionChange(e) {
      this.ids = e.map(item => {
        return item.mediumId;
      }).join(',');
      this.handleExportIds();
    },
    handleExportIds() {
      this.$emit('handleExportIds', this.ids);
    },
    handleSelectionChange(e) {
      e.sort(this.compare('$index'));
      this.selectItem = e;
    },
    compare(p) { // 这是比较函数
      return function(m, n) {
        var a = m[p];
        var b = n[p];
        return a - b; // 升序
      };
    },
    // 排序
    sortMethod(a) {
      const params = {
        sortType: -1,
        sortName: ''
      };
      if (a.order) {
        params.sortType = a.order === 'ascending' ? 1 : -1;
        params.sortName = a.prop;
      }
      this.$emit('sortMediumData', params);
    },
    // 翻页
    handleCurrentChange(page) {
      this.$emit('toPage', { page });
    },
    handleSizeChange(size) {
      this.$emit('toPage', { size });
    },
    toDetail(scope) {
      this.$router.push({
        name: 'detailResource',
        params: {
          resourceId: scope.row.mediumId
        }
      });
    },
    async toEdit(data, key) {
      const result = await getResouceInfo(data.mediumId);
      if (result.code === 200) {
        this.$refs[key].openDialog(result);
      } else {
        this.$message.error(result.message);
      }
    },
    // 根据签约状态展示对应内容
    hasContract({ signDetailStatus }) {
      return [2, 5].includes(signDetailStatus);// 已签约、已续约
    },
    handleContent({ signDetailStatus }) {
      switch (signDetailStatus) {
        case 1:return '无合同';
        case 6:return '无新合同';
        default:return '--';
      }
    },
    signStatusColor(status) {
      const signStatus = [1, 2, 5, 6];// 已签约的状态
      return signStatus.includes(status) ? '#31CC9C' : '#406EFF';
    },
    getMediumData() {
      this.$emit('getMediumData');
    },
    editCallBack({ params }) {
      this.$emit('editInfoCallBack', params.mediumId);
    },
    /*
    * 备注相关
    */
    // 修改备注弹出窗
    editRemarkMaskShow(item) {
      this.$refs.editRemarkMask.tabMaskShow(item);
    },
    // 修改备注在列表的显示
    mutedUpdateMediumList(mediumId) {
      this.$emit('mutedUpdateMediumList', mediumId);
    },
    /*
    * 案例相关
    */
    // 修改案例弹出窗
    editCaseMaskShow(item) {
      this.$refs.editCaseMask.tabMaskShow(item);
    },
    freshCaseList(casesItem) {
      this.$refs.editCaseMask.tabMaskShow(casesItem, true);
    },
    /*
    * 修改信息
    */
    toChangeName(item) {
      this.tableVisible = true;
      this.activeMediumId = item.mediumId;
    },
    handleClose() {
      this.tableVisible = false;
      this.activeMediumId = null;
    },
    tableRowClassName({ row, rowIndex }) {
      let baseClass = '';
      if (row.status === 0) {
        baseClass = baseClass + ' invalid-class';
      }
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]) ? `table-selected ${baseClass}` : baseClass;
      }
      return baseClass;
    },
    isSelect(row) {
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]);
      }
      return false;
    },
    // 展示订单弹窗
    showOrderDialog(item) {
      this.resourceMediumId = item.mediumId;
      this.$refs.orderListDialog.openDialog();
    },
    // 签约设置
    setSignStatusDialogOpen() {
      if (this.multipleSelectionAll.length === 0) {
        this.$message.warning(`请选择需要设置签约状态的账号资源`);
        return;
      }
      this.$refs['setSignStatusRef'].initDialog();
    },
    signStatusChange(status) {
      const params = {};
      params.ids = this.multipleSelectionAll.map(i => i[this.idKey]).join(',');
      params.signStatus = status;
      this.signSetLoading = true;
      setSignStatus(params).then(res => {
        this.signSetLoading = false;
        if (res.code === 200) {
          this.$refs['setSignStatusRef'].handleDialogClose();
          this.$message.success('设置成功');
          this.getMediumData();
          this.clearMixinSelection();
        }
      }).catch(e => {
        this.signSetLoading = false;
        console.log(e);
      });
    },
    getSelectedData() {
      return this.multipleSelectionAll.length ? this.multipleSelectionAll : null;
    },
    quicklyCreate(label, name) {
      this.$emit('quicklyCreate', label, name);
    },
    mergeShow() {
      this.$emit('mergeShow');
    },
    editInfo(data, auth) {
      this.$refs.EditInfoDialogRef.openDialog(data, auth);
    },
    getTip(auth, scope) {
      return !(this.hasRouteAuth(auth) && scope.row.isEditAuth) ? '无此内容编辑权限' : '';
    },
    getType(auth, scope) {
      return !(this.hasRouteAuth(auth) && scope.row.isEditAuth) ? 'disabledTip' : '';
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__fixed-right {
  .medium-expand-container {
    padding-left: 800px;
  }
}
::v-deep  .el-table {
  .el-table__fixed-right {
    box-shadow: -5px -8px 6px 0px rgba(240,242,245,0.81);
  }
  .el-table__body-wrapper::-webkit-scrollbar, .el-table__fixed-body-wrapper::-webkit-scrollbar   {
    width: 6px !important;
    height: 12px !important;
  }
  &.el-table--scrollable-y {
    .el-table__fixed-right {
      right: 6px !important;
      bottom: 0 !important;
    }
  }
}

.resource-table {
  position: relative;
  min-height: 100px;
  .gray-filter {
    filter: grayscale(100%);
  }
  ::v-deep {
    .invalid-class {
      .cell,.resource-name {
        color: #999 !important;
      }
    }
    .edit-column {
      padding: 0;
      &:hover {
        .edit-info {
          visibility: visible;
        }
      }
      .cell {
        height: 100%;
        display: flex;
        align-items: center;
        & > div {
          width: 100%;
        }
      }
    }
    .el-pagination__jump{
      margin-left: 0;
    }
  }
}
.edit-column {
  padding: 0;
  &:hover {
    .edit-info {
      visibility: visible;
    }
  }
  .cell {
    height: 100%;
    display: flex;
    align-items: center;
    & > div {
      width: 100%;
    }
  }
}
.edit-info {
  position: absolute;
  right: 0;
  top: 0;
  width: 0;
  height: 0;
  border-top: 36px solid #EFF3FB;
  border-left: 36px solid transparent;
  visibility: hidden;
  z-index: 3;
  cursor: pointer;
  &::after {
    content: '';
    width: 12px;
    height: 12px;
    position: absolute;
    top: -32px;
    right: 3px;
    background-image: url(../../../assets/medium/edit.png);
    background-repeat: no-repeat;
    background-size: 100%;
  }
}
.row-isSelect {
  background-color: #F3F5FB;
}
.list-btn {
  padding: 0;
  width: 96px;
  height: 28px;
  ::v-deep span {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.btn-list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.btn-icon {
  width: 14px;
  height: 14px;
  cursor: pointer;
  background-size: 100%;
  &.look {
    background-image: url('~@/assets/medium/goDetail.png');
    &:hover {
      background-image: url('~@/assets/medium/goDetailActive.png');
    }
  }
  &.edit {
    background-image: url('~@/assets/medium/editResource.png');
    &:hover {
      background-image: url('~@/assets/medium/editResourceActive.png');
    }
  }
  &.changeName {
    background-image: url('~@/assets/medium/changname.png');
    &:hover {
      background-image: url('~@/assets/medium/changnameActive.png');
    }
  }
}
.mb16 {
  margin-bottom: 16px;
}
</style>
